<?php

class Default_Model_AbstractDatabase
{
    protected $_db;

    protected function _initDb( $dataBaseName )
    {
        $options = array(
            '1002' => "SET NAMES utf8"
        );
        
        $this->_db = Zend_Db::factory('Pdo_Mysql', array(
            'host'                => 'localhost',
            'username'           => 'root',
            'password'           => 'pass',
            'dbname'             => $dataBaseName,
            'driver_options'    => $options
        ));

        return $this->_db;

    }

    /**
     * Get table data by data base and table names
     * @param string $dataBaseName
     * @param string $tableName
     * @return array
     */
    public function getTableData($dataBaseName, $tableName)
    {

        $this->_initDb($dataBaseName);

        $sql = 'SELECT * FROM ' . $dataBaseName . '.' . $tableName;

        return $this->_db->fetchAll($sql);

    }

    /**
     * Get the name of primary key of table by it's name and name of the data base
     * @param string $dataBaseName
     * @param string $tableName
     * @return string
     */
    public function getPrimaryKeyOfTabel($dataBaseName, $tableName)
    {
        $this->_initDb($dataBaseName);
        
        $dataBaseName = $this->_db->quote($dataBaseName);
        $tableName = $this->_db->quote($tableName);

        $sql = 'SELECT COLUMN_NAME FROM information_schema.KEY_COLUMN_USAGE
        WHERE TABLE_SCHEMA = ' . $dataBaseName . ' AND TABLE_NAME = ' . $tableName . ' AND
        CONSTRAINT_NAME = \'PRIMARY\'';

        $row = $this->_db->fetchRow($sql);

        return $row['COLUMN_NAME'];
    }

    
    /**
     * Create new row in table of data base
     * @param array $rowData
     * @param string $dataBaseName
     * @param string $tableName
     * @return array or bool
     */
    public function createRow($rowData, $dataBaseName, $tableName)
    {
        $this->_initDb($dataBaseName);
        $data = array();

        foreach ($rowData as $column => $value) {
            $data[$column] = $value;
        }

        if ( $this->_db->insert($tableName, $data) )
        {
            $primary['value'] = $this->_db->lastInsertId();
            $primary['name'] = $this->getPrimaryKeyOfTabel($dataBaseName, $tableName);
            return $primary;
        } else
        {
            return false;
        }

    }

    /**
     * Delete row in table of data base where Primary key is $rowData
     * @param array $rowData
     * @param string $dataBaseName
     * @param string $tableName
     * @return int
     */
    public function deleteRow($rowData, $dataBaseName, $tableName)
    {

        $this->_initDb($dataBaseName);
        $primaryKey = $this->getPrimaryKeyOfTabel($dataBaseName, $tableName);

        return $this->_db->delete($tableName, "$primaryKey = $rowData");

    }
    
}